package com.mistralcoast.rule34;

import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.res.AssetManager;
import android.os.AsyncTask;

public abstract class TagFetcher extends AsyncTask<Void, Long, Boolean>
		implements PropertyChangeListener {

	protected final DefaultHttpClient mClient = Common.getGzipHttpClient();
	InputStream in = null;
	
	public TagFetcher() {
		
	}
	
	public ArrayList<String> getTagsFromFile(Activity activity) {
		try {
			return getTags(getFileReader(activity));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ArrayList<String>();
	}
	
	public ArrayList<String> getTagsFromServer() {
		try {
			return getTags(getHttpReader());
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ArrayList<String>();
	}
	
	private BufferedReader getHttpReader() throws ClientProtocolException, IOException {
		HttpGet request = null;
			request = new HttpGet("http://rule34.paheal.net/tags");
		HttpResponse response = mClient.execute(request);
		in = response.getEntity().getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		return reader;
	}
	
	private BufferedReader getFileReader(Activity activity) throws IOException {
		AssetManager assetManager = activity.getAssets();
		InputStreamReader in = new InputStreamReader(
            assetManager.open("tags.htm"));
		BufferedReader reader = new BufferedReader(in);
		return reader;
	}
	
	private ArrayList<String> getTags(BufferedReader reader) {
		ArrayList<String> tagList = new ArrayList<String>();
		final String HREF_START = "href='/post/list/";
		final String HREF_END = "/1'>";
		final String NAME_START = "1'>"; //might not be needed
		final String NAME_END = "</a>";  //might not be needed
		try {
            String line = reader.readLine();
            String href = null;
//        	String name = null;
            
        	while (line !=null && !line.contains("id='Tagsmain'")) {
	            line = reader.readLine();
            }
        	
        	//rrcontent div isn't unique, looking for the one after Tagsmain
            while (line !=null && !line.contains("div class='rrcontent'")) {
	            line = reader.readLine();
            }
            
            while (line!= null && !line.contains("div class='rrbot'")) {
            	line = reader.readLine();
            	if(!line.contains(HREF_START)||
        			!line.contains(HREF_END)||
        			!line.contains(NAME_START)||
        			!line.contains(NAME_END))
        				continue;
            	href = line.substring(line.indexOf(HREF_START)+HREF_START.length(), line.indexOf(HREF_END));
//            	name = line.substring(line.indexOf(NAME_START)+NAME_START.length(), line.indexOf(NAME_END));
            	System.out.println("HREF : "+href);
            	tagList.add(href);
            }
            if(null!=in)in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return tagList;
	}
	
	public ArrayList<String> getTags() {
		return null;
	}
	
	/*private static Entry parseEntry(String content) throws ParserException
	  {
	    final Entry entry = new Entry();

	    final NodeVisitor linkVisitor = new NodeVisitor() {
	      
	      @Override
	      public void visitTag(Tag tag) {
	        String name = tag.getTagName();

	        if ("a".equalsIgnoreCase(name))
	            {
	              String hrefValue = tag.getAttribute("href");
	              if (hrefValue != null && !hrefValue.startsWith("http://"))
	              {
	                if (!hrefValue.startsWith("/")) hrefValue = "/"+hrefValue;
	                hrefValue = "http://javablogs.com"+hrefValue;
	                //System.out.println("test, value="+hrefValue);
	              }
	              if (hrefValue != null)
	              {
	                hrefValue = hrefValue.replaceAll("&", "&amp;");
	                tag.setAttribute("href", hrefValue);                
	              }
	            }
	      }
	    
	    };
	    
	    NodeVisitor visitor = new NodeVisitor() {

	      @Override
	      public void visitTag(Tag tag) {        
	        String name = tag.getTagName();
	            if ("span".equalsIgnoreCase(name) || "div".equalsIgnoreCase(name))
	            {              
	              String classValue = tag.getAttribute("class");
//	                LOGGER.debug("visittag name="+name+" class="+classValue+"children="+tag.getChildren().toHtml());
	              if ("blogentrydetails".equals(classValue))
	              {
	                Pattern countPattern = Pattern.compile("Reads:\\s*([0-9]*)");
	                Matcher matcher = countPattern.matcher(tag.getChildren().toHtml());
	                if (matcher.find())
	                {
	                  String countStr = matcher.group(1);
	                  entry.count = new Integer(countStr).intValue();
	                }
	                
	              }
	              else if ("blogentrysummary".equals(classValue))
	              {
	                try
	                {
	                  tag.getChildren().visitAllNodesWith(linkVisitor);
	                }
	                catch (ParserException pe)
	                {
	                	pe.printStackTrace();
	                }
	                entry.description = tag.getChildren().toHtml();                 
	                entry.description = entry.description.replaceAll("\\s+", " ");
	              }
	              else if ("blogentrytitle".equals(classValue))
	              {
	                try
	                {
	                  tag.getChildren().visitAllNodesWith(linkVisitor);
	                }
	                catch (ParserException pe)
	                {
	                	pe.printStackTrace();
	                }
	                entry.title =tag.getChildren().toHtml(); 
	                entry.title = entry.title.replaceAll("\\s+", " ");
	              }              
	            }
	            
	      }

	    };
	    Parser parser = new Parser(new Lexer(new Page(content,"UTF-8")));
	    parser.visitAllNodesWith(visitor);
	        if (entry.title != null)
	        {
	          return entry;
	        }
	        else return null;
	  }*/
}
